import { defineStore } from 'pinia'
import { 
  getDictTypeList, 
  createDictType, 
  updateDictType, 
  deleteDictType,
  getDictDataList,
  getDictDataByType,
  createDictData,
  updateDictData,
  deleteDictData
} from '@/api/dict'

export const useDictStore = defineStore('dict', {
  state: () => ({
    dictTypeList: [],
    dictTypeTotal: 0,
    dictDataList: [],
    dictDataTotal: 0,
    dictDataByType: {},
    loading: false,
    // 用于缓存正在进行的请求，避免重复请求
    pendingRequests: {}
  }),

  actions: {
    async fetchDictTypeList(params) {
      this.loading = true
      try {
        const response = await getDictTypeList(params)
        this.dictTypeList = response.data.records || []
        this.dictTypeTotal = response.data.total || 0
        return response.data
      } catch (error) {
        throw error
      } finally {
        this.loading = false
      }
    },

    async createDictType(data) {
      try {
        return await createDictType(data)
      } catch (error) {
        throw error
      }
    },

    async updateDictType(id, data) {
      try {
        return await updateDictType(id, data)
      } catch (error) {
        throw error
      }
    },

    async deleteDictType(id) {
      try {
        return await deleteDictType(id)
      } catch (error) {
        throw error
      }
    },

    async fetchDictDataList(params) {
      this.loading = true
      try {
        const response = await getDictDataList(params)
        this.dictDataList = response.data.records || []
        this.dictDataTotal = response.data.total || 0
        return response.data
      } catch (error) {
        throw error
      } finally {
        this.loading = false
      }
    },

    async fetchDictDataByType(params) {
      const dictType = params.code
      // 如果已经有缓存数据，直接返回
      if (this.dictDataByType[dictType]) {
        return this.dictDataByType[dictType]
      }
      
      // 如果已经有相同的请求正在进行，返回该请求的Promise
      if (this.pendingRequests[dictType]) {
        return this.pendingRequests[dictType]
      }
      
      try {
        // 创建新的请求Promise并缓存
        const requestPromise = getDictDataByType(params)
        this.pendingRequests[dictType] = requestPromise
        
        const response = await requestPromise
        this.dictDataByType[dictType] = response || []
        return response
      } catch (error) {
        // 请求失败时，从pendingRequests中移除
        delete this.pendingRequests[dictType]
        throw error
      } finally {
        // 请求完成后，从pendingRequests中移除
        delete this.pendingRequests[dictType]
      }
    },
    
    // 获取字典数据（带缓存）
    getDictData(dictType) {
      return this.dictDataByType[dictType] || []
    },
    
    // 清除指定字典类型的缓存
    clearDictCache(dictType) {
      delete this.dictDataByType[dictType]
    },
    
    // 清除所有字典缓存
    clearAllDictCache() {
      this.dictDataByType = {}
      this.pendingRequests = {}
    },
    
    // 强制重新加载指定字典类型
    async reloadDictData(params) {
      const dictType = params.code
      this.clearDictCache(dictType)
      return await this.fetchDictDataByType(params)
    },

    async createDictData(data) {
      try {
        return await createDictData(data)
      } catch (error) {
        throw error
      }
    },

    async updateDictData(id, data) {
      try {
        return await updateDictData(id, data)
      } catch (error) {
        throw error
      }
    },

    async deleteDictData(id) {
      try {
        return await deleteDictData(id)
      } catch (error) {
        throw error
      }
    },

    getDictLabel(dictType, dictValue) {
      const dictData = this.dictDataByType[dictType] || []
      const item = dictData.find(d => d.dictValue === String(dictValue))
      return item ? item.dictLabel : dictValue
    }
  }
})